package com.briup.sxau.web.Interceptor;

import com.briup.sxau.util.SxauException;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 自定义拦截器
 *  1.实现接口HandlerInterceptor
 *  @Component 会将当前类标记为spring的组件   会创建该类对象 交给ioc容器
 */
@Slf4j
@Component
public class SxauInterceptor implements HandlerInterceptor {
    /**
     * 在进入控制器之前 进行拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        日志记录请求方式和请求路径
        log.info(request.getMethod()+":"+request.getRequestURL());
//        获取请求头部的token
        String token = request.getHeader("token");
        if (ObjectUtils.isEmpty(token)){
            throw  new SxauException("用户未登录");
        }else {
            try {
                Jwt jwt = Jwts.parser().setSigningKey("briupadam").parse(token);
                return true;
            }catch (ExpiredJwtException e){
                throw  new SxauException("登录信息已经过期请重新登录");
            }catch (MalformedJwtException e){
                throw  new SxauException("非法token");
            }

        }

    }
}
